"""
Case Type   : gs_preupgradechk工具
Case Name   : 验证gs_preupgradechk工具A1项检测
Create At   : 2025/11/17
Owner       : chen
Description :
    1.gs_preupgradechk检测A1检查项指定日志文件
    2.使用命令直接检测
Expect      :
    1.成功
    2.成功
History     :
"""

import unittest
import os
import re
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

LOG = Logger()
primary_sh = CommonSH('PrimaryDbUser')


class Tools_Gs_Preupgradechk_TestCase0007(unittest.TestCase):
    def setUp(self):
        LOG.info(f'----{os.path.basename(__file__)} start----')
        self.pri_node = Node('PrimaryDbUser')
        self.com = Common()
        self.log_file = 'log_preupgradechk_007'
        LOG.info("---SetUp：检查数据库状态是否正常---")
        status = primary_sh.get_db_cluster_status()
        LOG.info(status)
        self.assertTrue("Degraded" in status or "Normal" in status)

    def test_gs_preupgradechk_tools(self):
        text = '----step1: gs_preupgradechk检测A1检查项指定日志文件; expect: 成功----'
        LOG.info(text)
        cmd = f"gs_preupgradechk -i A1 -l{self.log_file}.log"
        LOG.info(cmd)
        result = self.pri_node.sh(f"source {macro.DB_ENV_PATH};"
                                    f"{cmd}").result()
        LOG.info(result)
        self.assertIn('Successfully checked cpu usage status', result)
        cmd = f'cat {self.log_file}*'
        result = self.pri_node.sh(cmd).result()
        LOG.info(result)
        self.assertIn('Successfully checked cpu usage status', result)

        text = '----step2: 使用命令直接检测; expect: 成功----'
        LOG.info(text)
        cmd = f"gs_preupgradechk -i A1"
        LOG.info(cmd)
        result = self.pri_node.sh(f"source {macro.DB_ENV_PATH};"
                                    f"{cmd}").result()
        LOG.info(result)
        self.assertIn('Successfully checked cpu usage status', result)
        pattern = r'\[([^\]]+)\][^[]*?CPU usage is at ([\d.]+)%'
        matches = re.findall(pattern, result)
        res_node = 0
        res_warning = 0
        res_error = 0
        res_normal = 0
        for instance, usage in matches:
            usage_float = float(usage)
            LOG.info(f"{instance}: {usage}%")
            res_node += 1
            if usage_float > 95:
                res_error += 1
            elif 85 < usage_float <= 95:
                res_warning += 1
            else:
                res_normal += 1
        node_num = self.com.get_node_num(self.pri_node)
        self.assertEqual(node_num, res_node)
        self.assertEqual(res_warning, result.count('[Warning]'))
        self.assertEqual(res_error, result.count('[Error]'))
        self.assertEqual(res_normal, result.count('[Normal]'))

    def tearDown(self):
        LOG.info('--------清理环境--------')
        cmd = f'rm -rf {self.log_file}*; rm -rf gs_local*'
        LOG.info(cmd)
        result = self.pri_node.sh(cmd).result()
        LOG.info(result)
        status = primary_sh.get_db_cluster_status("detail")
        LOG.info(status)
        self.assertTrue("Degraded" in status or "Normal" in status)
        LOG.info(f"------{os.path.basename(__file__)} end------")
